package com.java;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author 黄嘉强
 * 构建一个browser对象，基于此对象向某些服务器发送请求，并读取服务端的响应
 */
public class Browser {
    public static void main(String[] args) throws IOException {
        // 1.定义要访问的服务地址和端口
        String host = "www.baidu.com";
        int port = 80;
        // 2.创建服务访问对象(java中为socket对象)
        Socket socket = new Socket(host, port);
        // 3.创建网络输入和输出流对象
        InputStream in = socket.getInputStream();
        // PrintWriter out = new PrintWriter(socket.getOutputStream());
        OutputStream out = socket.getOutputStream();
        // 4.基于输出流(OutputStream)对象向服务端写数据，表示发送请求
        // out.println("GET / HTTP/1.1\n");
        // out.println("\n\r");
        out.write("GET / HTTP/1.1\n\r".getBytes());
        out.write("\n\r".getBytes());
        out.flush();


        // 5.基于输入流(InputStream)对象读取服务端响应的结果
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = (in.read(buffer))) != -1) {
            System.out.println(new String(buffer,0,len));
        }

        in.close();
        out.close();
    }
}
